"""


"""
from flask import current_app
from flask import g, jsonify
from flask import redirect
from flask import request
from flask import session

from info import constants
from info import db
from info.models import News, Category
from info.utils.common import user_login_data
from info.utils.qiniu_storage import storage
from info.utils.response_code import RET
from . import profile_blu
from flask import render_template


@profile_blu.route("/info")
@user_login_data
def info():

    # 获取用户登录信息
    user = g.user
    # 如果没有登录，重定向到首页
    if not user:
        return redirect("/")

    # 添加测试数据
    # try:
    #     for i in range(199, 263):
    #         user.collection_news.append(News.query.get(i))
    #     db.session.commit()
    # except Exception as e:
    #     current_app.logger.error(e)
    #     db.session.rollback()
    #     return jsonify(errno=RET.DBERR, errmsg="数据库操作失败")

    data = {
       "user": user.to_dict() if user else None
    }
    return render_template("news/user.html", data=data)



@profile_blu.route("/base_info", methods=["GET", "POST"])
@user_login_data
def base_info():
    """
    渲染 user_base_info.html   get
    处理 保存基本资料 请求     post

    处理 保存基本资料 请求:
    1,获取参数
    2,判空校验
    3,保存数据到数据库  (session中的数据要更新)
    4,返回操作成功

    """
    # 获取用户登录信息
    user = g.user
    # 如果没有登录，重定向到首页
    if not user:
        return redirect("/")

    if request.method == "GET":

        data = {
            "user": user.to_dict() if user else None
        }
        return render_template("news/user_base_info.html", data=data)

    # 1, 获取参数
    data_dict = request.json
    signature = data_dict.get("signature")
    nick_name = data_dict.get("nick_name")
    gender = data_dict.get("gender")
    # 2, 判空校验
    if not all([signature, nick_name, gender]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误1")
    if gender not in("MAN", "WOMAN"):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误2")
    # 3, 保存数据到数据库(session中的数据要更新)
    user.signature = signature
    user.nick_name = nick_name
    user.gender = gender

    try:
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="数据库操作失败")

    session["nick_name"] = nick_name
    # 4, 返回操作成功
    return jsonify(errno=RET.OK, errmsg="保存成功")


@profile_blu.route("/pic_info", methods=["GET", "POST"])
@user_login_data
def pic_info():
    """
    渲染 user_pic_info.html   get
    处理 长传头像 请求     post


    """
    # 获取用户登录信息
    user = g.user
    # 如果没有登录，重定向到首页
    if not user:
        return redirect("/")

    if request.method == "GET":

        data = {
            "user": user.to_dict() if user else None
        }
        return render_template("news/user_pic_info.html", data=data)

    """

    1, 获取参数，参数就是上传来的图片 读取 .read()
    2, 上传图片到七牛云
    3, 保存图片路径到 user的avatar_url字段
    4, 返回成功, 同时返回路径给ajax的回调函数
    """
    # 1, 获取参数，参数就是上传来的图片 读取 .read()
    try:
        avatar_file = request.files.get("avatar").read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    # 2, 上传图片到七牛云
    try:
        avatar_url = storage(avatar_file)  # 上传图片到七牛云,并且返回图片名
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR,errmsg="上传图片出错")

    # 3, 保存图片路径到 user的avatar_url字段
    user.avatar_url = avatar_url
    try:
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="数据库操作失败")

    # 4, 返回成功, 同时返回路径给ajax的回调函数
    return jsonify(errno=RET.OK,errmsg="操作成功", data={"avatar_url": constants.QINIU_DOMIN_PREFIX + avatar_url})


@profile_blu.route("/pass_info", methods=["GET", "POST"])
@user_login_data
def pass_info():
    """
    渲染 user_pass_info.html   get
    处理 修改密码 请求     post


    """
    # 获取用户登录信息
    user = g.user
    # 如果没有登录，重定向到首页
    if not user:
        return redirect("/")

    if request.method == "GET":

        data = {
            "user": user.to_dict() if user else None
        }
        return render_template("news/user_pass_info.html", data=data)

    """
    1, 获取参数
    2, 判空校验
    3, 修改密码
    4, 返回操作成功
    """
    # 1, 获取参数
    data_dict = request.json
    old_password = data_dict.get("old_password")
    new_password = data_dict.get("new_password")
    new_password2 = data_dict.get("new_password2")
    # 2, 判空校验
    if not all([old_password, new_password, new_password2]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    if new_password != new_password2:
        return jsonify(errno=RET.PARAMERR, errmsg="两次新密码不一致")
    if not user.check_passowrd(old_password):
        return jsonify(errno=RET.PARAMERR, errmsg="密码错误")
    # 3, 修改密码
    user.password = new_password
    try:
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="数据库操作失败")

    # 4, 返回操作成功
    return jsonify(errno=RET.OK, errmsg="修改成功")


@profile_blu.route("/collection")
@user_login_data
def collection():
    """

    处理 展示用户收藏过得新闻 请求

    """
    # 获取用户登录信息
    user = g.user
    # 如果没有登录，重定向到首页
    if not user:
        return redirect("/")

    # 1, 获取参数，校验
    p = request.args.get("p", 1)
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1

    # 2, 分页查询
    try:
        paginate = user.collection_news.paginate(p, constants.USER_COLLECTION_MAX_NEWS)
        cur_page_news = paginate.items
        current_page = paginate.page
        total_page = paginate.pages

    except Exception as e:
        current_app.logger.error(e)

    # 把对象列表，转成字典列表
    cur_page_news_list = []
    for i in cur_page_news:
        cur_page_news_list.append(i.to_dict())

    # 3, 返回成功  ？
    data = {
        "cur_page_news_list": cur_page_news_list,
        "current_page":current_page,
        "total_page": total_page
    }
    return render_template("news/user_collection.html", data=data)


@profile_blu.route("/news_list")
@user_login_data
def news_list():
    """

    处理 展示用户发布过的新闻 请求

    """
    # 获取用户登录信息
    user = g.user
    # 如果没有登录，重定向到首页
    if not user:
        return redirect("/")

    # 1, 获取参数，校验
    p = request.args.get("p", 1)
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1

    # # 2, 分页查询
    try:
        paginate = user.news_list.order_by(News.create_time.desc()).paginate(p, constants.USER_COLLECTION_MAX_NEWS)
        cur_page_news = paginate.items
        current_page = paginate.page
        total_page = paginate.pages

    except Exception as e:
        current_app.logger.error(e)
    #
    # # 把对象列表，转成字典列表
    cur_page_news_list = []
    for i in cur_page_news:
        cur_page_news_list.append(i.to_review_dict())

    # # 3, 返回成功  ？
    data = {
        "cur_page_news_list": cur_page_news_list,
        "current_page":current_page,
        "total_page": total_page
    }
    return render_template("news/user_news_list.html", data=data)


@profile_blu.route("/news_release", methods=["GET", "POST"])
@user_login_data
def news_release():
    """
    渲染 user_news_release.html   get
    处理 发布新闻 请求     post


    处理 发布新闻 请求 :
    1, 获取参数，判空
    2, 上传图片到七牛云
    3, 创建News模型对象， 设置属性
    4, 添加到数据库，提交
    5, 返回发布成功
    """
    # 获取用户登录信息
    user = g.user
    # 如果没有登录，重定向到首页
    if not user:
        return redirect("/")

    if request.method == "GET":
        # 查询所有新闻分类
        try:
            categories = Category.query.all()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR,errmsg="数据库查询失败")


        data = {
            "user": user.to_dict() if user else None,
            "categories": categories
        }
        return render_template("news/user_news_release.html", data=data)

    # 1, 获取参数，判空
    data_dict = request.form
    title = data_dict.get("title")
    category_id = data_dict.get("category_id")
    index_image = request.files.get("index_image")
    digest = data_dict.get("digest")
    content = data_dict.get("content")
    source = "个人发布"
    if not all([title, category_id, index_image, digest, content]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    # 2, 上传图片到七牛云
    try:
        image_file = index_image.read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR,errmsg="图片读取错误")

    try:
        image_url = storage(image_file)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg="第三方错误")

    # 3, 创建News模型对象， 设置属性
    news = News()
    news.title = title
    news.category_id = category_id
    news.index_image_url = constants.QINIU_DOMIN_PREFIX + image_url
    news.digest = digest
    news.content = content
    news.source = source

    news.user_id = user.id
    news.status = 1   # 设置新闻的审核状态 为 审核中
    # 4, 添加到数据库，提交
    try:
        db.session.add(news)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="数据库操作失败")

    # 5, 返回发布成功
    return jsonify(errno=RET.OK, errmsg="发布成功")